	/*
	 * Function initializes validation, calls function to create table 
	 */
var jsondata="";
	$(document).ready(function() {
		
		getUncontacted();

    });
 
    function   getUncontacted()
    {
     	$.ajax({
    		url:'http://localhost:8080/easyskool/rest/userauthservice/getUncontacted',
    		type:'POST',
    		data: '{}',
    		dataType: 'json',
    		contentType: "application/json; charset=utf-8",
    		success:function (data,testStatus,response) {
    			 jsondata =JSON.parse(response.responseText);
    			var x = document.getElementById("contacts");
    			for(var i=0;i<jsondata.length;i++)
    			{		var option = document.createElement("option");
    			option.text = jsondata[i].cfName;
    			option.value=jsondata[i].rowId;
    			x.add(option);
    			}
    		},
    	error:function (data,testStatus,response) {
			alert("Error occured in getting Uncontacted Contacts");
//			window.location = "http://localhost:8080/easyskool/Login/login.jsp";		 
		}
 	
		});
    	
    }
	function storefollowUpDetails()
	{
		if($('#followUpForm').valid()) {
			formData = ($('#followUpForm').serializeArray());
	 alert( converter(formData));
			$.ajax({
			    url : 'http://localhost:8080/easyskool/rest/Webadmin/insertfollowUpDetails',
				type : 'POST',
				async: false,
				data :converter(formData),
				dataType : 'json',
				contentType : "application/json; charset=utf-8",
				success : function(data,testStatus,jqXHR) {
					var json = jQuery.parseJSON(jqXHR.responseText);
						if(json.create == "success"){
							//window.location = "http://localhost:8080/easyskool/WebPages/Masters/MasterSectionHome.jsp";
							alert("Record Successfully Stored..");
						} else	{
							alert("Error: ! "+ jqXHR.responseText);
						}
				},
			error : function(data,testStatus,jqXHR) {
				alert("error occured");
			}
		    });
	    	}
	}
    function fillContactdata(rowId)
    {
    	for(var i=0;i<jsondata.length;i++)
		{		 
    		if(jsondata[i].rowId==rowId)
    			{ 
    			document.getElementById('cfEmail').value=jsondata[i].cfEmail;
    			document.getElementById('cfMobile').value=jsondata[i].cfMobile;
    			document.getElementById('cfType').value=jsondata[i].cfType;
    			document.getElementById('cfReason').value=jsondata[i].cfReason;
    			document.getElementById('uaCode').value=jsondata[i].uaCode;
    			document.getElementById(jsondata[i].cfNeedAdvertisement).checked = true;
    			return;
    			
    			}
		}
    }
	/*
	 * Creates table with header row and pagination footer bar
	 * 
	 * Calls
	 * 
	 * createTableHeader()
	 * <String> - toAppend
	 * <String[]> - Table headers Array
	 * <boolean> - true to attach select all checkbox in header row 
	 */    
    function createMyTable() {
    	var toAppend = "";
    	//var tableId = "mytable";
    	var theaders = ["First Name",
    	                "Admin Email",
    	                "School City",
    	                "Last Name",
    	                "School Name",
    	                "Update",
    	                "Delete"];
    	toAppend +=	"<table class='table form-fields table-striped tablesorter' id='mytable'>";
    	toAppend = createTableHeader(toAppend, theaders, false);
		toAppend = attachPaginationBarToTable(toAppend);
		toAppend += "</table>";
		
		$("#tableDiv").append(toAppend);
    }
    
    /*
     * Create table from data collected by json Retrieve
     * 
     * Remove old table using ID
     * Create new table
     * For each row
     *     Start table row
     *     Add Checkbox to row
     *     Convert json item to table columns
     *     Add Update button
     *     Add Delete button
     *     End Table Row
     * Refresh Table Sorter
     * Re-attach click event to Update, Delete buttons, Checkbox     
     *
     * Calls
     * 
     * startTableRow()
     * <String> - toAppend
     * <int> - Attr id of row
     * 
     * addCheckboxToTableRow()
     * <String> - toAppend
     * <String> - Attr name of checkbox
     * <int> - Attr id of checkbox
     * 
     * jsonItemToString()
     * <String> - toAppend
     * <json> - part of json item from database
     * <String[]> - Array of names of hidden columns ["sectionName","createdDate"]
     * 
     * addButtonWithModalToTable()
     * <String> - toAppend
     * <String> - Display String of button
     * <String> - Css class for button
     * <String> - Attr Id of button
     * <String> - Modal Name called by button in which data from current row is populated
     * 
     * addButtonWithoutModalToTable()
     * <String> - toAppend
     * <String> - Display String of button
     * <String> - Css class for button
     * <String> - Attr Id of button
     * 
     * endTableRow()
     * <String> - toAppend
     * 
     * refreshTableSorter()
     * 
     * attachClickEventToUpdateButton()
     * 
     * attachClickEventToDeleteButton()
     * 
     * attachClickEventToSelectAllCheckBox()
     * 
     * return <void>
     */
    function refreshMyTable()
    {    	$.ajax({
    		url:'http://localhost:8080/easyskool/rest/Webadmin/getSchoolRequests',
    		type:'POST',
    		data: '{"user":"user","whereClause":'+null+'}',
    		dataType: 'json',
    		async: false,
    		contentType: "application/json; charset=utf-8",
    		success:function (data,testStatus,response) {
    			var jsondata =JSON.parse(response.responseText);
    			var toAppend = "";
    			var hiddenCols = [	"createdDate","requestStatusChangedBy","requestStatusChangedDate","schoolCode","scAddress","scState","scCountry","scPin","admMname","admAddress","admCity","admState","admCountry","admPin","aaPassword","scNoOfStudents","aaSecurityQ1","aaSecurityA1","aaSecurityQ2","aaSecurityA2","aaMobileNumber","requestStatus","scAffliation"
    			            		];
    			$("#mytable").remove();
    			createMyTable();
    			
    			$("#mytable").append("<tbody id='tbodyId'>");
    			$.each(jsondata, function(i, item) {
    				toAppend = "";
    				toAppend = startTableRow(toAppend, i);
    				toAppend = addLinkInFirstColumn(toAppend, item, hiddenCols,i);
    				toAppend = addButtonWithoutModalToTable(toAppend, 'Accept', 'btn btn-info', 'accept');
    				toAppend = addButtonWithoutModalToTable(toAppend, 'Reject', 'btn btn-danger', 'reject');
    				toAppend = endTableRow(toAppend);
    				$("#mytable").append(toAppend);
    			});
    			$("#mytable").append("</tbody>");
    		}
		});
    	
    	refreshTableSorter();
    	attachClickEventToHyperlink();
    	attachClickEventToRejectButton();
    	attachClickEventToAcceptButton();
    }
   
    /*
     * Attach click event to update button on table row
     * Populate values in Modal form from columns in current row
     * Needs to handle table column - dropdown, radiobutton, checkbox, date etc.
     * 
     *  Calls tableRowToModalForm()
     *  
     *  <tr> - Current table row
     *  <String> - Char('u') { ModalFormInputName(usectionId) - TableColName(sectionId) }
     *  <String> - Form name
     *  
     *  return <void>
     */
    function attachClickEventToHyperlink() {
    	$('#mytable').on('click', '#schoolName', function(){
        	tableRowToModalTable($(this).closest('tr'),'u','updateForm');
       });
    }
    
    /*
     * Fills values of table columns of particular row to Modal form
     * 
     * <tr> tr - Table row to be converted\
     * <String> preIndex - Char('u') { ModalFormInputName(usectionId) - TableColName(sectionId) }
     * <String> formName - Modal Form Name
     * 
     * return <void>
     */
    function tableRowToModalTable(tr, preIndex, formName) {

    	var curRowId = tr.attr('id');
    	tr.find('td').each(
    			function() {
    				if ($(this).children('input').length > 0
    						|| $(this).children('button').length > 0) {
    				} else {
    					$(
    							'form#' + formName + ' input[id=' + preIndex
    									+ $(this).attr('class') + ']').val(
    							$('#' + curRowId + ' td.' + $(this).attr('class'))
    									.text());
    				}
    			});

    	tr.find('td.hidden').each(
    			function() {
    				if ($(this).children('input').length > 0
    						|| $(this).children('button').length > 0) {
    				} else {
    					$(
    							'form#' + formName + ' input[id=' + preIndex
    									+ $(this).attr('class') + ']').val(
    							$('#' + curRowId + ' td.' + $(this).attr('class'))
    									.text());
    				}
    			});
    }
    function addLinkInFirstColumn(toAppend, item, hiddenCols,i)
    {
    	 
    	$.each(item, function(key, value) {
    		var found = $.inArray(key, hiddenCols) > -1;
    		if (found == false) {
    			if(key=='scName')
    				toAppend = toAppend + "<td class='" + key + "'><a data-toggle='modal' id='schoolName' data-target='#myInfoModal'>" + value + "</a></td>";
    			else
    				toAppend = toAppend + "<td class='" + key + "'>" + value + "</td>";
    		}
    		else {
    				toAppend = toAppend + "<td class='" + key + "' hidden='true'>"
    					+ value + "</td>";
    		}
    	 
    		// alert(key + "," + value);
    		 
    	});

    	return toAppend;
    }

    /*
     * Refresh Table Sorter Widget after table content is changed
     * 
     * return <void>
     */
    function refreshTableSorter() {
    	
    	$(function() {

			$.extend($.tablesorter.themes.bootstrap, {
				// these classes are added to the table. To see other table classes available,
				// look here: http://twitter.github.com/bootstrap/base-css.html#tables
				table      : 'table table-bordered',
				caption    : 'caption',
				header     : 'bootstrap-header', // give the header a gradient background
				footerRow  : '',
				footerCells: '',
				icons      : '', // add "icon-white" to make them white; this icon class is added to the <i> in the header
				sortNone   : 'bootstrap-icon-unsorted',
				sortAsc    : 'icon-chevron-up glyphicon glyphicon-chevron-up',     // includes classes for Bootstrap v2 & v3
				sortDesc   : 'icon-chevron-down glyphicon glyphicon-chevron-down', // includes classes for Bootstrap v2 & v3
				active     : '', // applied when column is sorted
				hover      : '', // use custom css here - bootstrap class may not override it
				filterRow  : '', // filter row class
				even       : '', // odd row zebra striping
				odd        : ''  // even row zebra striping
			});

			// call the tablesorter plugin and apply the uitheme widget
			$("#mytable").tablesorter({
				// this will apply the bootstrap theme if "uitheme" widget is included
				// the widgetOptions.uitheme is no longer required to be set
				theme : "bootstrap",

				widthFixed: true,

				headerTemplate : '{content} {icon}', // new in v2.7. Needed to add the bootstrap icon!

				// widget code contained in the jquery.tablesorter.widgets.js file
				// use the zebra stripe widget if you plan on hiding any rows (filter widget)
				widgets : [ "uitheme", "filter", "zebra" ],

				widgetOptions : {
					// using the default zebra striping class name, so it actually isn't included in the theme variable above
					// this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden
					zebra : ["even", "odd"],

					// reset filters button
					filter_reset : ".reset"

					// set the uitheme widget to use the bootstrap theme class names
					// this is no longer required, if theme is set
					// ,uitheme : "bootstrap"

				}
			})
			.tablesorterPager({

				// target the pager markup - see the HTML block below
				container: $(".ts-pager"),

				// target the pager page select dropdown - choose a page
				cssGoto  : ".pagenum",

				// remove rows from the table to speed up the sort of large tables.
				// setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled.
				removeRows: false,

				// output string - default is '{page}/{totalPages}';
				// possible variables: {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows}
				output: '{startRow} - {endRow} / {filteredRows} ({totalRows})'

			});

		});
		
		$(function(){

				// filter button demo code
				$('button.filter').click(function(){
					var col = $(this).data('column'),
						txt = $(this).data('filter');
					$('#mytable').find('.tablesorter-filter').val('').eq(col).val(txt);
					$('#mytable').trigger('search', false);
					return false;
				});

				// toggle zebra widget
				$('button.zebra').click(function(){
					var t = $(this).hasClass('btn-success');

					$('#mytable')
						.toggleClass('table-striped')[0]
						.config.widgets = (t) ? ["uitheme", "filter"] : ["uitheme", "filter", "zebra"];
					$(this)
						.toggleClass('btn-danger btn-success')
						.find('i')
						.toggleClass('icon-ok icon-remove glyphicon-ok glyphicon-remove').end()
						.find('span')
						.text(t ? 'disabled' : 'enabled');
					$('#mytable').trigger('refreshWidgets', [false]);
					return false;
				});
			});
    }
    
    /*
     * Attach click event to update button on table row
     * Populate values in Modal form from columns in current row
     * Needs to handle table column - dropdown, radiobutton, checkbox, date etc.
     * 
     *  Calls tableRowToModalForm()
     *  
     *  <tr> - Current table row
     *  <String> - Char('u') { ModalFormInputName(usectionId) - TableColName(sectionId) }
     *  <String> - Form name
     *  
     *  return <void>
     */
    function attachClickEventToUpdateButton() {
    	$('#mytable').on('click', '#update', function(){
        	tableRowToModalForm($(this).closest('tr'),'u','updateForm');
       });
    }
    /**
     * 
     */
    function findSchoolCode(tr)
    {
    	var i = 0, j = 0, keys = [], obj, ret = [];
    	obj = {};
    	tr.find('td').each(
    			function() {
    				//alert("CLASS"+$(this).attr('class'));
    				if ($(this).children('input').length > 0
    						|| $(this).children('button').length > 0) {
    				} else {
    					if($(this).attr('class')=='schoolCode')
    					{keys.push($(this).attr('class'));
    					obj[keys[j++]] = $(this).text();}
    					if($(this).attr('class')=='admEmail')
    					{keys.push($(this).attr('class'));
    					obj[keys[j++]] = $(this).text();}
    					
    				}
    			});
    	ret.push(JSON.stringify(obj));
    	alert(JSON.stringify(obj));
    	return ret;
    }
    
    /*
     * Attach click event to delete button on table row
     * Delete single row after confirm
     * Refresh Table after delete if successful
     * 
     * Calls refreshMyTable()
     * 
     * return <void>
     */
    function attachClickEventToRejectButton() {
     
    	$('#mytable').on('click', '#reject', function(){
    	 
        	
        	var curRowId = $(this).closest('tr');
        	$("#myConfirmModal").modal('show');
        	
        	$('#confirmDelete').click(function() {
        	 
        		$("#myConfirmModal").modal('hide');
               	$.ajax({
               		url : 'http://localhost:8080/easyskool/rest/Webadmin/rejectSchoolRequest',
           			type : 'POST',
           			data : '{"user":"aa","whereClause" :' +findSchoolCode(curRowId)+ '}',
           			dataType : 'json',
           			async: false,
           			contentType : "application/json; charset=utf-8",
           			success : function(data,testStatus,response) {
           				var json = jQuery.parseJSON(response.responseText);
           				if(json.update == "success"){
           					alert("Request has been rejected");
           					refreshMyTable();
           				} else	{
           					alert("Request has not been rejected");
           					refreshMyTable();           				}
           			}
               	});
//               	refreshMyTable();
                
            });
        	
        	$('#cancelDelete').click(function() {
        		$("#myConfirmModal").modal('hide');
        	
        	});
        	
        });
    }
    
    /*
     * Attach click event to delete button on table row
     * Delete single row after confirm
     * Refresh Table after delete if successful
     * 
     * Calls refreshMyTable()
     * 
     * return <void>
     */
    function attachClickEventToAcceptButton() {
    	 	$('#mytable').on('click', '#accept', function(){
    		 
        	
        	var curRowId = $(this).closest('tr');
        	$("#myConfirmModal").modal('show');
        	
        	$('#confirmDelete').click(function() {
        		 $("#myConfirmModal").modal('hide');
        		 $('#tableDiv').fadeTo('slow',.6);
        	$('#tableDiv').append('<div id="cover" style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');
               	$.ajax({
               		url : 'http://localhost:8080/easyskool/rest/Webadmin/acceptSchoolRequest',
           			type : 'POST',
           			data : '{"user":"aa","whereClause" :' + tableRowToObj(curRowId) + '}',
           			dataType : 'json',
           			async: false,
           			contentType : "application/json; charset=utf-8",
           			success : function(data,testStatus,response) {
           				var json = jQuery.parseJSON(response.responseText);
           				if(json.update == "success"){
           					alert("Request has been accepted");
           					refreshMyTable();
           				} else	{
           					alert("Request has not been accepted");
           					refreshMyTable();           				}
           			}
               	});
               	var element = document.getElementById('cover');
               	element.parentNode.removeChild(element);
               	$('#tableDiv').fadeTo('slow',1);
//               	refreshMyTable();
                
            });
        	
        	$('#cancelDelete').click(function() {
        		$("#myConfirmModal").modal('hide');
        	
        	});
        	
        });
    }
    
      

    
    